package com.example.springblog.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class JWTUtils {
    //设置token的过期时间
    public static final long Expiration = 60*60*1000;//一个小时后过期：ms

    //设置密钥
    private static final String secretString = "GYqjk9DwkEMA7PF9vg0NYrGNwLAxyI5quMcKcMssgFc=";
    //生成安全密钥
    private static final SecretKey KEY =
            Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String genJwt(Map<String,Object> claim){
        //签名算法
        String jwt = Jwts.builder()
                .setClaims(claim)//自定义内容（负载
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+Expiration))//设置过期时间
                .signWith(KEY)//签名算法
                .compact();
        return jwt;
    }

    //校验令牌
    public static Claims parseJWT(String jwt){
        if(!StringUtils.hasLength(jwt)){
            return null;
        }
        /*//创建解析器，设置签名密钥
        JwtParser build = Jwts.parserBuilder().setSigningKey(KEY).build();
        Claims claims = null;

        try {
            //解析token
            claims = build.parseClaimsJws(jwt).getBody();
        } catch (ExpiredJwtException e) {
            //签名校验失败
            log.error("令牌过期：jwt{}",jwt);
        } catch (Exception e){
            log.error("jwt校验失败，jwt:",jwt);
        }
        return claims;*/

        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(secretString);
        Claims claims = null;
        try {
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();

        }catch (Exception e){
            log.error("令牌解析错误jwt:",jwt);

        }
        return claims;
    }

    //从token中获取用户id
    public static Integer getUserIdFromToken(String jwtToken){
        Claims claims = JWTUtils.parseJWT(jwtToken);
        if(claims!=null){
            Map<String,Object> userInfo = new HashMap<>(claims);
            return (Integer) userInfo.get("id");
        }
        return null;
    }
}
